{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install scikit-learn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[code learn from](https://scikit-learn.org/stable/auto_examples/linear_model/plot_ols)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import math\n",
    "\n",
    "from sklearn import datasets, linear_model\n",
    "from sklearn.metrics import mean_squared_error, r2_score\n",
    "\n",
    "# 加载糖尿病数据集 数据集说明 https://www4.stat.ncsu.edu/~boos/var.select/diabetes.html\n",
    "diabetes_X, diabetes_y = datasets.load_diabetes(return_X_y=True)\n",
    "\n",
    "# 只使用十个体征中的第三个特征（体重指数）\n",
    "diabetes_X = diabetes_X[:, np.newaxis, 2]\n",
    "\n",
    "# 7/3分\n",
    "split=math.ceil(diabetes_X.shape[0]*0.7)\n",
    "\n",
    "# 按照比例分为训练/测试集\n",
    "diabetes_X_train = diabetes_X[:split]\n",
    "diabetes_X_test = diabetes_X[split:]\n",
    "\n",
    "# 按照比例分为训练/测试集\n",
    "diabetes_y_train = diabetes_y[:split]\n",
    "diabetes_y_test = diabetes_y[split:]\n",
    "\n",
    "# 创建线性回归对象\n",
    "regr = linear_model.LinearRegression()\n",
    "\n",
    "# 使用训练集训练模型\n",
    "regr.fit(diabetes_X_train, diabetes_y_train)\n",
    "\n",
    "# 使用测试集进行预测\n",
    "diabetes_y_pred = regr.predict(diabetes_X_test)\n",
    "\n",
    "# 系数\n",
    "print(\"系数: \\n\", regr.coef_)\n",
    "# 均方误差\n",
    "print(\"均方误差: %.2f\" % mean_squared_error(diabetes_y_test, diabetes_y_pred))\n",
    "# 确定系数：1为完美预测\n",
    "print(\"决定系数: %.2f\" % r2_score(diabetes_y_test, diabetes_y_pred))\n",
    "\n",
    "# 绘图输出\n",
    "plt.scatter(diabetes_X_test, diabetes_y_test, color=\"black\")\n",
    "plt.plot(diabetes_X_test, diabetes_y_pred, color=\"blue\", linewidth=3)\n",
    "\n",
    "# plt.xticks(())\n",
    "# plt.yticks(())\n",
    "plt.rcParams['font.sans-serif'] = ['SimHei']\n",
    "plt.title(\"糖尿病与体重指数相关\")\n",
    "plt.xlabel('体重指数',fontproperties = 'SimHei')\n",
    "plt.ylabel('疾病标志物测定')\n",
    "\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "586c3cdf86f3a3a1181be60287eeea244d671c39d2199c05edac4d89c647599f"
  },
  "kernelspec": {
   "display_name": "Python 3.9.6 64-bit",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
